//
//  DetailViewController.m
//  滴滴快拍
//
//  Created by dllo on 16/5/21.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "DetailViewController.h"
#import "Header.h"
#import "FindDetail.h"
#import "UIImageView+WebCache.h"
#import <Masonry/Masonry.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "DetailTableViewCell.h"
#import "ZFPlayer.h"
#import "FMDBTool.h"
#import "MJRefresh.h"
#import "AppDelegate.h"
#import "WeiboSDK+Statistics.h"
#import "StatisticsDemoRootViewController.h"
@interface DetailViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource
>
@property (nonatomic, strong)NSMutableArray *categoryArr;
@property (nonatomic, strong)BaseTableView *tableView;
@property (nonatomic, strong)BaseImageView *headBackImageView; // 头视图的背景图
@property (nonatomic, strong)BaseImageView *picImageView; // 头像图片
@property (nonatomic, strong)BaseLabel *titleLabel; // 名字
@property (nonatomic, strong)BaseLabel *detailLabel; // 详细介绍
@property (nonatomic, strong)NSString *urlStr; // 视频连接
@property (nonatomic, strong)ZFPlayerView *playerView;

@property (nonatomic, strong)NSNumber *count;
@property (nonatomic, assign)BOOL isAttention; // 关注
@property (nonatomic, assign)NSInteger i;

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"个人主页";
    [[FMDBTool shareFMDBTool] openDB];
    [[FMDBTool shareFMDBTool] createTable];
    
    
     self.isAttention = [[FMDBTool shareFMDBTool] columnExists:self.findModel.name inTableWithName:@"channel"];
    NSString *buttonTitle = self.isAttention ? @"已关注" : @"关注";
    
   
    [[FMDBTool shareFMDBTool]openFavoriteDB];
    [[FMDBTool shareFMDBTool] createFavoriteTable];

    
    BaseButton *button = [BaseButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 60, 24);
    [button setTitle:buttonTitle forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:button]];
    button.layer.cornerRadius = 5;
    if (self.isAttention == NO) {
         button.backgroundColor =  [UIColor colorWithRed:255 / 255.0 green:211 / 255.0 blue:63 / 255.0 alpha:1];
    }else {
        button.backgroundColor = [UIColor colorWithRed:232 / 255.0 green:232 / 255.0 blue:232 / 255.0 alpha:1];
    }
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self createView];
    [self createData];
    
    self.i = 2;
   
 
    
}


- (void)buttonClick:(BaseButton *)button {
    if (self.isAttention == NO) {
         button.backgroundColor = [UIColor colorWithRed:232 / 255.0 green:232 / 255.0 blue:232 / 255.0 alpha:1];
        [button setTitle:@"已关注" forState:UIControlStateNormal];
       
        [[FMDBTool shareFMDBTool] insertChannel:self.findModel];
    }else {
        button.backgroundColor =   [UIColor colorWithRed:255 / 255.0 green:211 / 255.0 blue:63 / 255.0 alpha:1];

        [button setTitle:@"关注" forState:UIControlStateNormal];
        [[FMDBTool shareFMDBTool] deleteChannel:self.findModel];
    
    }
    
    self.isAttention = !self.isAttention;

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];

}






- (void)createData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:[NSString stringWithFormat:@"http://api.miaopai.com/m/shot_channel.json?deviceId=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&vend=miaopai&token=&uuid=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&timestamp=1463798836257&live=1&f_type=v2&suid=%@&os=android&likeStat=1&unique_id=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&version=6.3.5&udid=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&channel=mobile360&page=1&per=20",self.str] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        [self saveData:responseObject DataName:@"hotMovieTable"];
        //        NSLog(@"%@", responseObject);
        NSDictionary *dic = responseObject;
        NSArray *result = dic[@"result"];
        self.categoryArr = [AGLChannel baseModalByArr:result];
        
        
        FindDetail *detail = [[FindDetail alloc] init];
        NSDictionary *dictionary = dic[@"header"];
        [detail setValuesForKeysWithDictionary:dictionary];
//        NSLog(@"%@",detail.icon);
        [self.headBackImageView sd_setImageWithURL:[NSURL URLWithString:detail.icon]];
        [self.picImageView sd_setImageWithURL:[NSURL URLWithString:detail.icon]];
        self.titleLabel.text = detail.nick;
        self.detailLabel.text = [detail.ext objectForKey:@"desc"];
        self.detailLabel.numberOfLines = 0;
        [self.detailLabel sizeToFit];
        self.detailLabel.textAlignment = NSTextAlignmentCenter;
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"首页分类联网失败");
        //        NSDictionary *dic = [self getDataWithDataName:@"hotMovieTable"];
        //        if (dic == nil) {
        //            NSLog(@"请连网啊亲");
        //        } else {
        //            NSDictionary *data = dic[@"data"];
        //            NSArray *hot = data[@"hot"];
        //            self.movieArr = [AGLMovie baseModalByArr:hot];
        //            [self.tableView reloadData];
        //        }
        //        
        
    }];

}

- (void)loadMoreData {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:[NSString stringWithFormat:@"http://api.miaopai.com/m/shot_channel.json?deviceId=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&vend=miaopai&token=&uuid=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&timestamp=1463798836257&live=1&f_type=v2&suid=%@&os=android&likeStat=1&unique_id=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&version=6.3.5&udid=d3e7b369-9e44-3e73-8cc6-260d6931cdbf&channel=mobile360&page=%ld&per=20",self.str,self.i] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        [self saveData:responseObject DataName:@"hotMovieTable"];
        //        NSLog(@"%@", responseObject);
        NSDictionary *dic = responseObject;
        NSArray *result = dic[@"result"];
        NSArray *arr = [AGLChannel baseModalByArr:result];
        [self.categoryArr addObjectsFromArray:arr];
        
        FindDetail *detail = [[FindDetail alloc] init];
        NSDictionary *dictionary = dic[@"header"];
        [detail setValuesForKeysWithDictionary:dictionary];
        //        NSLog(@"%@",detail.icon);
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"首页分类联网失败");
        //        NSDictionary *dic = [self getDataWithDataName:@"hotMovieTable"];
        //        if (dic == nil) {
        //            NSLog(@"请连网啊亲");
        //        } else {
        //            NSDictionary *data = dic[@"data"];
        //            NSArray *hot = data[@"hot"];
        //            self.movieArr = [AGLMovie baseModalByArr:hot];
        //            [self.tableView reloadData];
        //        }
        //
        
    }];

    self.i++;

}


- (void)createView {
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    BaseView *headView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
//     FindDetail *detail = [[FindDetail alloc] init];
    self.headBackImageView = [[BaseImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyRefresh = NO;
    self.tableView.mj_footer = footer;
#pragma mark - 毛玻璃
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blur];
    effectView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200);
    [self.headBackImageView addSubview:effectView];
    [headView addSubview:self.headBackImageView];
    // 头像
    self.picImageView = [[BaseImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 40, 40, 80, 80)];
    self.picImageView.layer.cornerRadius = 40;
    self.picImageView.layer.masksToBounds = YES;
    [headView addSubview:self.picImageView];
    // 名字
    self.titleLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(0, 130, SCREEN_WIDTH, 20)];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:self.titleLabel];
    // 详细介绍
    self.detailLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(20, 160, SCREEN_WIDTH - 40, 20)];
    [headView addSubview:self.detailLabel];
    self.detailLabel.font = [UIFont systemFontOfSize:15];
    [self.tableView.tableHeaderView addSubview:headView];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];// tableView 取消下划线
    [self.tableView registerClass:[DetailTableViewCell class] forCellReuseIdentifier:NSStringFromClass([DetailTableViewCell class])];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.categoryArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DetailTableViewCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone; // cell 点击不改变颜色
    AGLChannel *channel = self.categoryArr[indexPath.row];
    NSString *buttonTitle = self.isAttention ? [NSString stringWithFormat:@"点赞 %d",self.count.intValue ] : [NSString stringWithFormat:@"点赞 %d",self.count.intValue + 1];
    [cell.favoriteButton setTitle:buttonTitle forState:UIControlStateNormal];

    [cell.relayButton setTitle:@"转发" forState:UIControlStateNormal];
    [cell.commentButton setTitle:[NSString stringWithFormat:@"评论 %@",channel.ccnt] forState:UIControlStateNormal];
    cell.titleLabel.text = channel.t;
    cell.titleLabel.numberOfLines = 0;
    [cell.titleLabel sizeToFit];
    __block AGLChannel *model = self.categoryArr[indexPath.row];
    cell.model = model;
    __block NSIndexPath *weakIndexPath = indexPath;
    __block DetailTableViewCell *weakCell     = cell;
    __weak typeof(self) weakSelf       = self;
    cell.playBlock = ^(BaseButton *btn) {
        weakSelf.playerView = [ZFPlayerView sharedPlayerView];
        NSURL *videoURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://gslb.miaopai.com/stream/%@.mp4", model.scid]];
        [weakSelf.playerView setVideoURL:videoURL withTableView:weakSelf.tableView AtIndexPath:weakIndexPath withImageViewTag:1000];
        weakSelf.playerView.hasDownload = YES;
        
        [weakSelf.playerView addPlayerToCellImageView:weakCell.picImageView];
        weakSelf.playerView.playerLayerGravity = ZFPlayerLayerGravityResizeAspect;
    };
    
    cell.isFavorite = [[FMDBTool shareFMDBTool] columnFavoriteExists:channel.icon inTableWithName:@"like"];
    cell.favoriteBlock = ^(BaseButton *button) {
        
        
        self.count = channel.lcnt;
        if (cell.isFavorite == NO) {
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [button setTitle:[NSString stringWithFormat:@"点赞 %d",self.count.intValue + 1] forState:UIControlStateNormal];
            [[FMDBTool shareFMDBTool] insertFavorite:channel];
        }else {
            [button setTitleColor:[UIColor colorWithRed:151 / 255.0 green:151 / 255.0 blue:151 / 255.0 alpha:1] forState:UIControlStateNormal];
            
            [button setTitle:[NSString stringWithFormat:@"点赞 %d",self.count.intValue] forState:UIControlStateNormal];
            [[FMDBTool shareFMDBTool] deleteFavorite:channel];
            
        }
        
        cell.isFavorite = !cell.isFavorite;
    
    };
    
    
    cell.shareBlock = ^(BaseButton *button) {
    
        AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
        authRequest.redirectURI = @"https://api.weibo.com/oauth2/default.html";
        authRequest.scope = @"all";
        
        WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
        request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                             @"Other_Info_1": [NSNumber numberWithInt:123],
                             @"Other_Info_2": @[@"obj1", @"obj2"],
                             @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
        //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
        [WeiboSDK sendRequest:request];
        

        
    };
    
    return cell;

}
- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
    //    NSString *str = [NSString stringWithContentsOfURL:self.videoURL encoding:nil error:nil];
    
    message.text = NSLocalizedString(self.findModel.url, nil);
    return message;
}




- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait) {
        self.view.backgroundColor = [UIColor whiteColor];
        //if use Masonry,Please open this annotation
        /*
         [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.view).offset(20);
         }];
         */
    }else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight || toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
        self.view.backgroundColor = [UIColor blackColor];
        //if use Masonry,Please open this annotation
        /*
         [self.playerView mas_updateConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.view).offset(0);
         }];
         */
    }
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 400;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.playerView resetPlayer];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
